package com.jiepos.mpos.biz.customer.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.xmlbeans.impl.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.biz.appInfM.service.MessageInfService;
import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.DBConstant.Code;
import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppCustomerInfoDao;
import com.jiepos.mpos.common.entity.App_Custom_InfEntity;
import com.jiepos.mpos.common.entity.GpsEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.DateUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.RSACoder;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 
 * 会员信息业务类
 * 
 * @ProjectName: [mpos1]
 * @Package com.jiepos.mpos.biz.customer.service
 * @author 肖志伟
 * @version 1.0
 * @since 2017年9月21日 下午5:59:46
 * @history（历次修订内容、修订人、修订时间等） @UpdateRemark [说明本次修改内容]
 * @Copyright (c) 2017 江苏杰博实信息技术有限公司
 */
@Service
public class AppCustomerInfoService extends BaseService {

	@Autowired
	private AppCustomerInfoDao appCustomerInfoDao;
	@Autowired
	private MessageInfService messageInfService;
	

	/**
	 * 查询会员信息Json分页数据
	 *
	 * @param request
	 * @param pagination
	 * @param appCustomerInfoEntity
	 * @param sup_custom_name
	 * @param ins_name
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map getCustomerInfoList(HttpServletRequest request, Pagination pagination,
			App_Custom_InfEntity appCustomerInfoEntity, String ins_name, String sup_custom_name,String sup_custom_no,
								   String realname_auth_ts_start,String realname_auth_ts_end) {
		StringBuffer sb = getInitSql("t1").append(", ");
		sb.append("t1.custom_uuid as uuid, t1.custom_no, ");
		sb.append("CONCAT (RPAD (SUBSTR (t1.login_id, 1, 3),LENGTH (t1.login_id) - 4,'*'),SUBSTR (t1.login_id,LENGTH (t1.login_id) - 3,4)) || NVL2(t1.name, '-'||t1.name, '') as name, ");
		sb.append("(select code_val||'-'||code_desc from " + Table.T_APP_CODE_LIST
				+ " where code_val = t1.user_st and code_tp = '" + DBConstant.Code.USER_ST + "') as user_st, ");
		sb.append("(SELECT t2.custom_no FROM " + Table.T_APP_CUSTOM_INF
				+ " t2 WHERE t2.custom_uuid = t1.sup_custom_uuid ) AS sup_custom_no,");
		sb.append("(SELECT CONCAT (RPAD (SUBSTR (t2.login_id, 1, 3),LENGTH (t2.login_id) - 4,'*'),SUBSTR (t2.login_id,LENGTH (t2.login_id) - 3,4)) || '-' || t2. NAME FROM " + Table.T_APP_CUSTOM_INF
				+ " t2 WHERE t2.custom_uuid = t1.sup_custom_uuid ) AS sup_custom_name,");
		sb.append("t3.ins_cd || '-' || t3.ins_cn_nm AS ins_name, ");
		sb.append("t4.area_cd || '-' || t4.area_cn_nm AS area_cn_name, ");
		sb.append("(select code_val||'-'||code_desc from " + Table.T_APP_CODE_LIST
				+ " where code_val = t1.realname_auth_st and code_tp = '" + DBConstant.Code.REALNAME_AUTH_ST
				+ "') as realname_auth_st, ");
		sb.append("(select code_val||'-'||code_desc from " + Table.T_APP_CODE_LIST
				+ " where code_val = t1.realname_audit_st and code_tp = '" + DBConstant.Code.REALNAME_AUDIT_ST
				+ "') as realname_audit_st, ");
		sb.append("(select code_val||'-'||code_desc from " + Table.T_APP_CODE_LIST
				+ " where code_val = t1.vip_st and code_tp = '" + DBConstant.Code.VIP_ST + "') as vip_st, ");
		sb.append("to_char(t1.vip_auth_ts, 'yyyy-mm-dd hh24:mi:ss') as vip_auth_ts, ");
		sb.append("to_char(t1.realname_auth_ts, 'yyyy-mm-dd hh24:mi:ss') as realname_auth_ts, ");
		sb.append("CONCAT (RPAD (SUBSTR (t1.certificate_no, 1, 6),LENGTH (t1.certificate_no) - 4,'*'),SUBSTR (t1.certificate_no,LENGTH (t1.certificate_no) - 3,4)) as certificate_no ");
		sb.append("from ");
		sb.append(Table.T_APP_CUSTOM_INF + " t1 ");
		sb.append("LEFT JOIN " + Table.T_APP_INS_INF + " t3 ON t1.ins_uuid = t3.ins_uuid ");
		sb.append("LEFT JOIN " + Table.T_APP_AREA_CD + " t4 ON t1.area_uuid = t4.area_uuid ");
		sb.append("where 1=1 ");
		List list = new ArrayList();
		if (!StringUtils.isBlank(appCustomerInfoEntity.getPhone())) {
			sb.append(" and t1.login_id like ? ");
			list.add("%" + appCustomerInfoEntity.getPhone() + "%");
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getName())) {
			sb.append(" and t1.name like ? ");
			list.add("%" + appCustomerInfoEntity.getName() + "%");
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getUser_st())) {
			sb.append(" and t1.user_st = ? ");
			list.add(appCustomerInfoEntity.getUser_st());
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getIns_uuid())) {
			sb.append(" and t1.ins_uuid = (select ins_uuid from " + Table.T_APP_INS_INF + " where ins_cd = ?) ");
			list.add(appCustomerInfoEntity.getIns_uuid());
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getCustom_no())) {
			sb.append(" and t1.custom_no = ? ");
			list.add(appCustomerInfoEntity.getCustom_no());
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getSup_custom_uuid())) {
			sb.append(" and t1.sup_custom_uuid IN (select custom_uuid from " + Table.T_APP_CUSTOM_INF
					+ " where login_id LIKE ?) ");
			list.add("%"+appCustomerInfoEntity.getSup_custom_uuid()+"%");
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getCertificate_no())) {
			sb.append(" and t1.certificate_no like ? ");
			list.add("%"+appCustomerInfoEntity.getCertificate_no()+"%");
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getRealname_audit_st())) {
			sb.append(" and t1.realname_audit_st = ? ");
			list.add(appCustomerInfoEntity.getRealname_audit_st());
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getRealname_auth_st())) {
			sb.append(" and t1.realname_auth_st = ? ");
			list.add(appCustomerInfoEntity.getRealname_auth_st());
		}
		if (!StringUtils.isBlank(appCustomerInfoEntity.getVip_st())) {
			sb.append(" and t1.vip_st = ? ");
			list.add(appCustomerInfoEntity.getVip_st());
		}
		if (!StringUtils.isBlank(ins_name)) {
			sb.append(" and t3.ins_cn_nm Like ? ");
			list.add("%" + ins_name + "%");
		}
		//推荐人姓名
		if (!StringUtils.isBlank(sup_custom_name)) {
			sb.append(" and t1.sup_custom_uuid IN (select custom_uuid from " + Table.T_APP_CUSTOM_INF
					+ " where name like ?) ");
			list.add("%" + sup_custom_name + "%");
		}
		//推荐人会员编号
		if (!StringUtils.isBlank(sup_custom_no)) {
			sb.append(" and t1.custom_no IN (SELECT t2.custom_no FROM " + Table.T_APP_CUSTOM_INF
					+ " t1 left join "+ Table.T_APP_CUSTOM_INF+" t2 on t1.custom_uuid = t2.sup_custom_uuid  where  t1.custom_no like ?) ");
			list.add("%" + sup_custom_no + "%");
		}
		//实名认证审核时间
		if(!StringUtils.isBlank(realname_auth_ts_start)){
			sb.append(" and TO_CHAR(t1.realname_auth_ts,'yyyyMMdd') >= ?");
			Date date = DateUtil.strToDate(realname_auth_ts_start, DateUtil.FORMAT_DATE_1);
			list.add(DateUtil.dateToStr(date, "yyyyMMdd"));
		}
		if(!StringUtils.isBlank(realname_auth_ts_end)){
			sb.append(" and TO_CHAR(t1.realname_auth_ts,'yyyyMMdd') <= ?");
			Date date = DateUtil.strToDate(realname_auth_ts_end,DateUtil.FORMAT_DATE_1);
			list.add(DateUtil.dateToStr(date,"yyyyMMdd"));
		}
		pagination.queryString = sb.toString();
	//	pagination = super.getInsAuthSql(request, pagination, "t1", null);
		pagination = super.getCustomAuthSql(request, pagination, "t1", null);
		pagination = this.getOrderSql(pagination, "t1");
		return appCustomerInfoDao.getPaginationMap(pagination, "t1", list);
	}

	/**
	 * 修改用户状态
	 *
	 * @param customer_uuids
	 * @param loginUser
	 * @param userSt
	 */
	public void updateUserSt(String customer_uuids, Map loginUser, String userSt) {
		appCustomerInfoDao.updateByIds("custom_uuid", customer_uuids, userSt,
				String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
	}

	/**
	 * 获取会员上下级关系菜单树业务功能
	 * @param request 
	 *
	 * @param id
	 * @param searchText 
	 * @return
	 */
	public List<Map<String, Object>> getCustomerRelationTree(HttpServletRequest request, String id, String searchText) {
		String sql = "select t1.custom_uuid as ID, t1.sup_custom_uuid as PID, "
				+ "t1.custom_no||'-'||CONCAT(RPAD(SUBSTR (t1.login_id, 1, 3),LENGTH(t1.login_id) - 4, '*'),SUBSTR(t1.login_id, LENGTH(t1.login_id) - 3, 4))||'['||t1.name||']' as NAME, "
				+ "(select count(*) from  "
				+ Table.T_APP_CUSTOM_INF + " where sup_custom_uuid = t1.custom_uuid) as isParent from "
				+ Table.T_APP_CUSTOM_INF + " t1 where 1 = 1 ";
		List list = new ArrayList();
		if(StringUtils.isBlank(searchText)){
			if (StringUtils.isBlank(id)) {
			//	sql += " and (t1.sup_custom_uuid = '' or t1.sup_custom_uuid is null) ";
			} else {
				sql += " and t1.sup_custom_uuid = ? ";
				list.add(id);
			}
		}else{
			sql += " and (t1.name LIKE ? or t1.login_id LIKE ? or t1.custom_no LIKE ? )";
			list.add("%"+searchText+"%");
			list.add("%"+searchText+"%");
			list.add("%"+searchText+"%");
		}
		sql = super.getCustomAuthSql(request, sql, "t1", null);
		List<Map<String, Object>> resultList = appCustomerInfoDao.queryForList(sql, list);
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		if(StringUtils.isBlank(searchText)){
			for (Map<String, Object> map : resultList) {
				map.put("isParent", map.get("ISPARENT"));
				result.add(map);
			}
		}else{
			result.addAll(resultList);
		}
		return result;
	}

	/**
	 * 根据会员的uuid获取会员的个人详细信息
	 *
	 * @param custom_uuid
	 * @return
	 */
	public Map getCustomerInfoByUUID(String custom_uuid) {
		StringBuffer sb = getInitSql("t1").append(", ");
		sb.append("t1.custom_uuid as uuid, t1.cstomer_type, t1.custom_no, t1.phone, t1.name, t1.user_st, ");
		sb.append("t1.login_id, t1.user_st, t1.nation, to_char(t1.vip_auth_ts,'yyyy-mm-dd hh24:mi:ss') as vip_auth_ts, t1.certificate_no, ");
		sb.append("(SELECT t2.login_id || '-' || t2.name FROM " + Table.T_APP_CUSTOM_INF
				+ " t2 WHERE t2.custom_uuid = t1.sup_custom_uuid ) AS sup_custom_name,");
		sb.append("t3.ins_cd || '-' || t3.ins_cn_nm AS ins_name, ");
		sb.append("t4.area_cd || '-' || t4.area_cn_nm AS area_cn_name, ");
		sb.append("t1.realname_audit_st, ");
		sb.append("to_char(t1.realname_auth_ts,'yyyy-mm-dd hh24:mi:ss') as realname_auth_ts, ");
		sb.append("t1.realname_auth_st, ");
		sb.append("t1.realname_audit_st, ");
		sb.append("t1.vip_st ");
		sb.append("from ");
		sb.append(Table.T_APP_CUSTOM_INF + " t1 ");
		sb.append("LEFT JOIN " + Table.T_APP_INS_INF + " t3 ON t1.ins_uuid = t3.ins_uuid ");
		sb.append("LEFT JOIN " + Table.T_APP_AREA_CD + " t4 ON t1.area_uuid = t4.area_uuid ");
		sb.append("where 1=1 ");
		List list = new ArrayList();
		if (!StringUtils.isEmpty(custom_uuid)) {
			sb.append("and t1.custom_uuid = ? ");
			list.add(custom_uuid);
		}
		Map<String, Object> result = null;
		List<Map<String, Object>> resultList = appCustomerInfoDao.queryForList(sb.toString(), list);
		if (!CollectionUtil.isEmpty(resultList)) {
			result = resultList.get(0);
		}
		return result;

	}

	/**
	 * 根据会员编号得到会员信息
	 * @param custom_no
	 * @return
	 */
	public Map getCustomerInfoByCustomNo(String custom_no){
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append(" select login_id          as \"login_id\", ")
				.append("        user_st           as \"user_st\", ")
				.append("		 custom_no 		   as \"custom_no\", ")
				.append("        name              as \"name\", ")
				.append("        certificate_no    as \"certificate_no\", ")
				.append("        realname_auth_st  as \"realname_auth_st\", ")
				.append("        vip_st            as \"vip_st\", ")
				.append("        realname_audit_st as \"realname_audit_st\" ")
				.append("   from  "+Table.T_APP_CUSTOM_INF)
				.append("  where rec_st != '0' ")
				.append("    and custom_no = ? ");
		List params = new ArrayList();
		params.add(custom_no);
		List<Map<String, Object>> list = appCustomerInfoDao.queryForList(sqlBuf.toString(), params);
		if(list != null && list.size()>0){
			return list.get(0);
		}else{
			return new HashMap();
		}
	}
	
	/**
	 * 保存会员实体
	 * @param customer
	 * @return
	 * @throws Exception 
	 */
	public App_Custom_InfEntity saveCustomer(App_Custom_InfEntity customer) throws Exception {
		customer.setCustom_no(IDFactoryUtil.getId());
		customer.setCustom_uuid(IDFactoryUtil.getUUID());
		customer.setCstomer_type(SystemConstant.CSTOMER_TYPE);
		customer.setUser_st(SystemConstant.USER_ST);
		customer.setLast_oper_in(SystemConstant.OPER_ADD);
		customer.setRec_st(SystemConstant.NORMAL_STATUS);
		customer.setCheck_login_count(SystemConstant.CHECK_LOGIN_COUNT);
		customer.setCertificate_type(SystemConstant.CERTIFICATE_TYPE_01);
		customer.setVip_st(SystemConstant.AUTH_ST_0);
		customer.setRec_crt_ts(new Timestamp(System.currentTimeMillis()));
		customer.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
		customer.setPass_word(getShareNewPassWord(customer.getPass_word(), customer.getLogin_id(), customer.getCustom_no()));
		customer.setPay_pass_word(getShareNewPassWord(customer.getPay_pass_word(), customer.getLogin_id(), customer.getCustom_no()));
		/*判断有无设置审核状态信息*/
		if(StringUtils.isBlank(customer.getRealname_audit_st())){
			customer.setRealname_audit_st(SystemConstant.REVIEW_ST_9); // 默认未审核
		}
		/*判断有无设置实名信息*/
		if(StringUtils.isBlank(customer.getRealname_auth_st())){
			customer.setRealname_auth_st(SystemConstant.AUTH_ST_0); // 默认未实名
		}
		appCustomerInfoDao.save(customer);

		return customer;
	}

	/**
	 * 新增注册会员信息
	 *
	 * @param gpsEntity
	 * @return
	 */
	public String addAppCustomer(String login_id, String pass_word, String pay_pass_word, String sup_custom_uuid, String insUuid) throws Exception {
		String customNo = IDFactoryUtil.getId();
		String loginPassWord = this.getNewPassWord(pass_word, login_id, customNo);
		String payPassWord = this.getNewPassWord(pay_pass_word, login_id, customNo);
		return addCustomer(customNo, login_id, loginPassWord, payPassWord, sup_custom_uuid, insUuid);
	}
	
	/**
	 * 分享注册新增会员
	 * @param login_id
	 * @param pass_word
	 * @param pay_pass_word
	 * @param sup_custom_uuid
	 * @param insUuid
	 * @return
	 * @throws Exception
	 */
	public String addShareCustomer(String login_id, String pass_word, String pay_pass_word, String sup_custom_uuid, String insUuid) throws Exception {
		String customNo = IDFactoryUtil.getId();
		String loginPassWord = this.getShareNewPassWord(pass_word, login_id, customNo);
		String payPassWord = this.getShareNewPassWord(pay_pass_word, login_id, customNo);
		return addCustomer(customNo, login_id, loginPassWord, payPassWord, sup_custom_uuid, insUuid);
	}
	
	private String addCustomer(String customNo, String login_id, String loginPassWord, String payPassWord, String sup_custom_uuid, String insUuid) throws Exception{
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append(" INSERT INTO t_App_Custom_Inf ")
				.append("   (custom_uuid, ")
				.append("    cstomer_type, ")
				.append("    custom_no, ")
				.append("    login_id, ")
				.append("    pass_word, ")
				.append("    user_st, ")
				.append("    check_login_count, ")
				.append("    phone, ")
				.append("    realname_auth_st, ")
				.append("    realname_audit_st, ")
				.append("    vip_st, ")
				.append("    sup_custom_uuid, ")
				.append("    pay_pass_word, ")
				.append("    last_oper_in, ")
				.append("    rec_crt_ts, ")
				.append("    rec_upd_ts, ")
				.append("    rec_st, ")
				.append("    rec_upd_usr_id,  ")
				.append("    ins_uuid ) ")
				.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ");
		log.debug("INSERT sql : " + sqlBuf);
		List<Object> params = new ArrayList<Object>();
		params.add(IDFactoryUtil.getUUID());
		params.add(SystemConstant.CSTOMER_TYPE);
		params.add(customNo);
		params.add(login_id);
		params.add(loginPassWord);//登陆密码
		params.add(SystemConstant.USER_ST);
		params.add(SystemConstant.CHECK_LOGIN_COUNT);
		params.add(login_id); //手机号 注册的logn_id
		params.add(SystemConstant.AUTH_ST_0); //实名认证状态默认0
		params.add(SystemConstant.REVIEW_ST_9); //审核状态默认9
		params.add(SystemConstant.AUTH_ST_0); //vip认证状态默认未认证
		params.add(sup_custom_uuid);//推荐手机号
		params.add(payPassWord);//支付密码
		params.add(SystemConstant.OPER_ADD);
		params.add(new Timestamp(System.currentTimeMillis()));
		params.add(new Timestamp(System.currentTimeMillis()));
		params.add(SystemConstant.NORMAL_STATUS);
		params.add(login_id);
		params.add(insUuid);
		
		//插入注册信息
		appCustomerInfoDao.insertCustomParm(sqlBuf.toString(), params);
		/*推送通知推荐人*/
		pushToSupCustomer(sup_custom_uuid, login_id);

		return SystemConstant.RSP_CODE;
	}

	/**
	 * 获取需要转加密的密码，并进行加密保存
	 *
	 * @param pass_word app传递过来的密码
	 * @param login_id  登录账号
	 * @param customNo  会员编号
	 * @return String MD5加密密码
	 * @throws Exception
	 */
	public String getNewPassWord(String pass_word, String login_id, String customNo) throws Exception {
		//登陆密码解密
		byte[] decodedData = RSACoder.decryptByPrivateKey(RSACoder.decryptBASE64(pass_word), SystemConstant.PRI_KEY_STR);
		String pwd = RSACoder.encryptBASE64(decodedData);
		//base64转码
		pwd = new String(Base64.decode(pwd.getBytes()));
		log.debug("解密后密码:{}", pwd);
		String passWord = pwd.replace(login_id, "");
		log.debug("原始密码:{}",  passWord);
		String newPassWord = StringUtils.MD5(customNo + passWord);
		return newPassWord;
	}

	/**
	 * Rsa加密
	 * @param pass_word
	 * @param login_id
	 * @param customNo
	 * @return
	 */
	public  String getEncryptByPub(String pass_word, String login_id, String customNo){
		byte[] rsaPublicKeys = new byte[0];
		try {
			//公钥加密
			log.debug("原始密码:{}", pass_word);
			rsaPublicKeys = RSACoder.encryptByPublicKey(RSACoder.decryptBASE64(pass_word), SystemConstant.PUB_KEY_STR);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//加密后的密码
		String pwd = RSACoder.encryptBASE64(rsaPublicKeys);
		log.debug("加密后密码:{}", pwd);
		String passWord = StringUtils.MD5(customNo + pwd);
		return passWord;
	}
	
	public String getShareNewPassWord(String pass_word, String login_id, String customNo) throws Exception {
		log.debug("登录账号:{}", login_id);
		log.debug("原始密码:{}",  pass_word);
		String newPassWord = StringUtils.MD5(customNo + pass_word);
		return newPassWord;
	}

	/**
	 * 获取机构号的ins_uuid
	 *
	 * @param gpsEntity 公共参数
	 * @return String ins_uuid
	 */
	public String getInsUuid(GpsEntity gpsEntity) {
		//ins_uuid  机构编号 判断是安卓还是ios
		String appType = gpsEntity.getAppType();
		StringBuilder sql = new StringBuilder();
		sql.append("select t1.ins_uuid ");
		sql.append(" from " + DBConstant.Table.T_APP_INS_APP + " t1 ");
		sql.append(" where t1.rec_st=" + SystemConstant.REC_ST_1);
		if (SystemConstant.APP_TYPE_IOS.equals(appType)) {
			sql.append(" and t1.ios_appid=?");
		} else {
			sql.append(" and t1.android_appid=?");
		}
		List paramList = new ArrayList();
		paramList.add(gpsEntity.getApp_id());
		List<Map<String, Object>> list = appCustomerInfoDao.queryForList(sql.toString(), paramList);
		if (CollectionUtil.isEmpty(list)) {
			return null;
		} else {
			Map customMap = list.get(0);
			String ins_uuid = String.valueOf(customMap.get("ins_uuid"));
			return ins_uuid;
		}
	}

	/**
	 * 根据会员编号查询
	 *
	 * @param custom_no
	 * @return
	 */
	public App_Custom_InfEntity getCustomByNo(String custom_no) {
		if (StringUtils.isBlank(custom_no) || custom_no.equals("undefined")) {
			return new App_Custom_InfEntity();
		}
		return appCustomerInfoDao.findByParam("custom_no", custom_no);
	}
	
	/**
	 * 查询会员信息实体 通过 custom_uuid
	 * @param custom_uuid
	 * @return
	 */
	public App_Custom_InfEntity getCustomByCustomUUID(String custom_uuid){
		if (StringUtils.isBlank(custom_uuid) || custom_uuid.equals("undefined")) {
			return null;
		}
		return appCustomerInfoDao.findByParam("custom_uuid",custom_uuid);
	}

	/**
	 * 根据登录账户得到会员信息
	 *
	 * @param login_id
	 * @return
	 */
	public App_Custom_InfEntity getCustomInfByLoginId(String login_id) {
		if (StringUtils.isBlank(login_id) || "undefined".equals(login_id)) {
			return null;
		}
		return appCustomerInfoDao.findByParam("login_id", login_id);
	}
	
	/**
	 * 根据手机号码查询会员信息
	 * @param phone
	 * @return
	 */
	public App_Custom_InfEntity getCustomInfByPhone(String phone) {
		if (StringUtils.isBlank(phone) || "undefined".equals(phone)) {
			return null;
		}
		return appCustomerInfoDao.findByParam("phone", phone);
	}

	/**
	 * 根据身份证号得到会员信息
	 * @param certificate_no
	 * @return
	 */
	public App_Custom_InfEntity getCustomInfByCertificateNo(String certificate_no){
		Object[] param1 = new Object[]{"certificate_no","realname_auth_st","rec_st"};
		Object[] param2 = new Object[]{certificate_no,SystemConstant.REVIEW_ST_1,SystemConstant.REC_ST_1};
		return appCustomerInfoDao.findByParamses(param1,param2);
	}


	/**
	 * 根据会员UUID得到该会员的推荐数量（两级）
	 * @param custom_uuid
	 * @return
	 */
	public String getRecommCount(String custom_uuid){
		//查询直接推荐人是该会员的会员uuid集合
		StringBuffer dirSql = new StringBuffer();
		dirSql.append(" SELECT CUSTOM_UUID ")
				.append("   FROM ")
				.append(DBConstant.Table.T_APP_CUSTOM_INF)
				.append("  WHERE SUP_CUSTOM_UUID = ? ");
		List<String> params = new ArrayList<>();
		params.add(custom_uuid);
		List<Map<String,Object>> dirList = appCustomerInfoDao.queryForList(dirSql.toString(), params);
		if(dirList != null && dirList.size() > 0){
			//推荐人数量
			int count = dirList.size();
			//查询间接推荐人是该会员的会员uuid集合
			StringBuffer indirSql = new StringBuffer();
			indirSql.append(" SELECT CUSTOM_UUID ")
					.append("           FROM  ")
					.append(DBConstant.Table.T_APP_CUSTOM_INF)
					.append("          WHERE 1 = 2 ");
			params.clear();
			for(Map<String,Object> map : dirList){
				indirSql.append(" OR SUP_CUSTOM_UUID = ? ");
				params.add(String.valueOf(map.get("CUSTOM_UUID")));
			}
			//间接推荐人是该会员的uuid集合
			List<String> indirList = appCustomerInfoDao.queryForList(indirSql.toString(), params);
			if(indirList != null && indirList.size() > 0){
				count += indirList.size();
			}
			return String.valueOf(count);
		}else{
			return "0";
		}
	}

	/**
	 * 忘记密码
	 *
	 * @param login_id
	 * @param newPwd
	 * @param rand
	 * @param gpsEntity
	 * @return
	 */
	public String forgetPwd(String login_id, String newPwd, String rand, GpsEntity gpsEntity) throws Exception {

		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append(" update " + Table.T_APP_CUSTOM_INF + " set ")
				.append("  pass_word = ? ,  ")
				.append("  rec_upd_ts =? ")
				.append("  where login_id =? ");
		List paramList = new ArrayList();
		paramList.add(newPwd);
		paramList.add(new Timestamp(System.currentTimeMillis()));
		paramList.add(login_id);
		appCustomerInfoDao.insertCustomParm(sqlBuf.toString(), paramList);
		return SystemConstant.RSPCODE_SUCCESS_MSG;
	}

	/**
	 * 修改用户登录错误次数
	 * @param custom_uuid
	 * @param count
	 */
	public void updateLoginCount(String custom_uuid,String count){
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("UPDATE ")
				.append(Table.T_APP_CUSTOM_INF)
				.append(" SET CHECK_LOGIN_COUNT = ?,REC_UPD_TS=SYSTIMESTAMP WHERE CUSTOM_UUID = ?");
		List<String> params = new ArrayList<>();
		params.add(count);
		params.add(custom_uuid);
		appCustomerInfoDao.update(sqlBuf.toString(),params);
	}

	/**
	 * 更新支付密码
	 * @param custom_uuid
	 * @param payPassword
	 */
	public void updatePayPassword(String custom_uuid,String payPassword){
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("UPDATE ")
				.append(Table.T_APP_CUSTOM_INF)
				.append(" SET PAY_PASS_WORD = ?,REC_UPD_TS=SYSTIMESTAMP WHERE CUSTOM_UUID = ?");
		List<String> params = new ArrayList<>();
		params.add(payPassword);
		params.add(custom_uuid);
		appCustomerInfoDao.update(sqlBuf.toString(),params);
	}

	/**
	 * 修改会员极光客户端id
	 * @param custom_uuid
	 * @param getui_clientid
	 */
	public void updateGetUIClientID(String custom_uuid, String appType, String getui_clientid){
		//去掉重复的个推id
		StringBuffer sb = new StringBuffer();
		sb.append("UPDATE ")
				.append(Table.T_APP_CUSTOM_INF)
				.append(" SET getui_clientid = null, REC_UPD_TS=SYSTIMESTAMP WHERE getui_clientid = ?");
		List<String> list = new ArrayList<>();
		list.add(getui_clientid);
		appCustomerInfoDao.update(sb.toString(),list);
		// 修改当前用户个推id
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("UPDATE ")
				.append(Table.T_APP_CUSTOM_INF)
				.append(" SET getui_clientid = ?, APPTYPE = ?, REC_UPD_TS=SYSTIMESTAMP WHERE CUSTOM_UUID = ?");
		List<String> params = new ArrayList<>();
		params.add(getui_clientid);
		params.add(appType);
		params.add(custom_uuid);
		appCustomerInfoDao.update(sqlBuf.toString(),params);
	}


	/**
	 * 四要素认证后更新会员信息
	 * @param custom_no 会员编号
	 * @param certificate_no 证件号码
	 * @param name 真实姓名
	 */
	public void updateCustomInfoAfterRealNameAuth(String custom_no,String certificate_no,String name,String review_st){
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("UPDATE ")
				.append(Table.T_APP_CUSTOM_INF)
				.append(" SET NAME = ?,CERTIFICATE_TYPE = '")
				.append(SystemConstant.CERTIFICATE_TYPE_01)
				.append("' ,CERTIFICATE_NO = ?,REALNAME_AUTH_ST = '")
				.append(SystemConstant.AUTH_ST_0)
				.append("',REALNAME_AUDIT_ST = ? ")
				.append(",REC_UPD_TS=SYSTIMESTAMP WHERE CUSTOM_NO = ?");
		List<String> params = new ArrayList<>();
		params.add(name);
		params.add(certificate_no);
		params.add(review_st);
		params.add(custom_no);
		appCustomerInfoDao.update(sqlBuf.toString(),params);
	}

	/**
	 * 更新用户审核状态
	 * @param login_id 登录id/手机号
	 * @param custom_no
	 * @param audit_st
	 */
	public void updateCustomAuditStatus(String login_id,String custom_no,String audit_st){
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append(" UPDATE  "+Table.T_APP_CUSTOM_INF)
				.append("    SET REALNAME_AUDIT_ST = ? , ")
				.append("        REC_UPD_TS = SYSTIMESTAMP, ")
				.append("        REC_UPD_USR_ID = ? , ")
				.append("        LAST_OPER_IN = '"+SystemConstant.OPER_UPDATE+"' ")
				.append("  WHERE CUSTOM_NO = ? ");
		List<String> params = new ArrayList<>();
		params.add(audit_st);
		params.add(login_id);
		params.add(custom_no);
		appCustomerInfoDao.update(sqlBuf.toString(),params);
	}


	/**
	 * 变更手机号
	 * @param login_id
	 * @param custom_no
	 * @param certificate_no
	 * @param new_login_id
	 * @return
	 */
	public String changeLoginId(HttpServletRequest request,String login_id, String custom_no, String certificate_no, String new_login_id) {
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append(" UPDATE ")
				.append(" "+Table.T_APP_CUSTOM_INF+" SET  ")
				.append("  login_id = ?, ")
				.append(" phone = ?, ")
				.append(" last_oper_in = ?, ")
				.append(" rec_upd_ts = ?, ")
				.append(" rec_upd_usr_id = ? ")
				.append("  where custom_no = ?  ");
		List listParams = new ArrayList();
		listParams.add(new_login_id);
		listParams.add(new_login_id);
		listParams.add(SystemConstant.OPER_UPDATE);
		listParams.add(new Timestamp(System.currentTimeMillis()));
		listParams.add("system");//当前用户
		listParams.add(custom_no);
		appCustomerInfoDao.update(sqlBuf.toString(),listParams);
		return  SystemConstant.RSP_MSG;
	}

	/**
	 * 修改密码
	 * @param request
	 * @param login_id
	 * @param custom_no
	 * @param newPwdRspCode
	 * @return
	 */
	public String changePassWord(HttpServletRequest request, String login_id, String custom_no, String newPwdRspCode,App_Custom_InfEntity appCustomInfEntity ) {
		String loginUser = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_USER));
		Map map = new HashMap();
		map.put(SystemConstant.SESSION_LOGIN_USER, loginUser);
		map.put("request", request);
		appCustomInfEntity.setPass_word(newPwdRspCode);
		appCustomInfEntity = (App_Custom_InfEntity) this.saveCommonData(appCustomInfEntity ,map,"update" );
		List noChangeList = new ArrayList();
		noChangeList.add("custom_uuid");
		noChangeList.add("rec_crt_ts");
		appCustomerInfoDao.update(appCustomInfEntity, noChangeList);
		return  SystemConstant.RSPCODE_SUCCESS_MSG;
	}
	
	/**
	 * 获取我的推荐用户 --直接
	 * @param custom_no
	 * @return
	 */
	public List getMyRecommendUser(String custom_no,String curr_page,String rows_perpage){
		Pagination pagination = new Pagination();
		pagination.setPage(Integer.parseInt(curr_page));
		pagination.setRows(Integer.parseInt(rows_perpage));
		StringBuffer sb = new StringBuffer();
		List<String> list = new ArrayList<>();
		sb.append(" SELECT custom_uuid FROM ")
			.append(Table.T_APP_CUSTOM_INF)
			.append(" WHERE sup_custom_uuid in (")
			.append(" select custom_uuid from ")
			.append(Table.T_APP_CUSTOM_INF)
			.append(" where custom_no = ?)");
		list.add(custom_no);
		
		List<Map<String, Object>> result = appCustomerInfoDao.queryForList(sb.toString(), list);
		
		if(CollectionUtil.isEmpty(result)){
			return null;
		}
		StringBuffer sb2 = new StringBuffer();
		sb2.append(" SELECT custom_no as \"recomd_custom_no\",CONCAT (RPAD (SUBSTR (t1.login_id, 1, 3),LENGTH (t1.login_id) - 4,'*'),SUBSTR (t1.login_id,LENGTH (t1.login_id) - 3,4)) AS \"custom_login_id\",")
			.append(" to_char(t1.rec_crt_ts,'yyyy-mm-dd hh24:mi:ss') as \"reg_tm\",t1.realname_auth_st as \"realname_auth_st\",t1.vip_st as \"vip_st\" FROM ").append(Table.T_APP_CUSTOM_INF)
			.append(" t1 where custom_uuid in (");		
		for(int i=0;i<result.size();i++){
			sb2.append("\'"+result.get(i).get("custom_uuid")+"\'");
			if(i<result.size()-1){
				sb2.append(",");
			}
		}
		sb2.append(") ORDER BY t1.rec_crt_ts DESC ");
		pagination.queryString = sb2.toString();
		pagination = appCustomerInfoDao.getPagination(pagination, "t1", null);
		List<Map<String, Object>> userList = pagination.getOldData();
		
		
		return userList;
	}
	
	/**
	 * 获取我的推荐用户详情
	 * @param custom_no
	 * @return
	 */
	public String getMyRecommendUserNumber(String login_id,String custom_no){
		StringBuffer sb = new StringBuffer();
		List list = new ArrayList<>();
		sb.append(" select COUNT(1) as direct_count_people from ").append(Table.T_APP_CUSTOM_INF)
			.append("  where sup_custom_uuid in ( select custom_uuid from ").append(Table.T_APP_CUSTOM_INF)
			.append("  where custom_no = ?)");
		list.add(custom_no);
		List<Map<String, Object>> countResult= appCustomerInfoDao.queryForList(sb.toString(), list);
		if(!CollectionUtil.isEmpty(countResult)){
			return StringUtils.objToString(countResult.get(0).get("direct_count_people"));
		}else {
			return "0";
		}
	}
	
	/**
	 * 获取我的推荐用户贡献分润
	 * @param login_id
	 * @param custom_no
	 * @return
	 */
	public String getMyRecommendProfit(String login_id,String custom_no){
		StringBuffer sb = new StringBuffer();
		List list = new ArrayList<>();
		sb.append(" SELECT to_char(sum(amount),'fm9999999990.00') as contri_profit from ").append(Table.T_APP_CUSTOM_ACCOUNT_CHANGE)
			.append(" where cur_custom_uuid in (select custom_uuid from T_APP_CUSTOM_INF where custom_no = ? )")
			.append(" and custom_uuid in (select custom_uuid from T_APP_CUSTOM_INF where login_id = ?)")
			.append(" and SERVICE_NO in ("+SystemConstant.SERVICE_NO_100005+")" );
		list.add(custom_no);
		list.add(login_id);
		List<Map<String, Object>> profitResult= appCustomerInfoDao.queryForList(sb.toString(), list);
		if(!CollectionUtil.isEmpty(profitResult)){
			return StringUtils.objToString(profitResult.get(0).get("contri_profit"));
		}else {
			return "0.00";
		}
	}
	
	/**
	 * 获取我的推荐用户贡献佣金
	 * @param login_id
	 * @param custom_no
	 * @return
	 */
	public String getMyRecommendCommission(String login_id,String custom_no){
		
		StringBuffer sb = new StringBuffer();
		List list = new ArrayList<>();
		sb.append(" SELECT to_char(sum(amount),'fm9999999990.00')  as contri_commission from ").append(Table.T_APP_CUSTOM_ACCOUNT_CHANGE)
			.append(" where cur_custom_uuid in (select custom_uuid from T_APP_CUSTOM_INF where custom_no = ? ) ")
			.append(" and custom_uuid in (select custom_uuid from T_APP_CUSTOM_INF where login_id = ?)")
			.append(" and SERVICE_NO in ("+SystemConstant.SERVICE_NO_100003+","+SystemConstant.SERVICE_NO_100004+")" );
		list.add(custom_no);
		list.add(login_id);
		List<Map<String, Object>> commisResult= appCustomerInfoDao.queryForList(sb.toString(), list);
		if(!CollectionUtil.isEmpty(commisResult)){
			return  StringUtils.objToString(commisResult.get(0).get("contri_commission"));
		}else {
			return "0.00";
		}
	}

	/**
	 * 修改会员的APP所属机构
	 * @param
	 * @param ins_cd
	 * @return
	 */
	public Boolean modifyCustomInsUuid( String custom_uuids, Map loginUser, String ins_cd) {
		appCustomerInfoDao.updateByCustomIds("custom_uuid", custom_uuids, ins_cd,
				String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
		return true;
	}
	
	/**
	 * 会员注册之后推送消息给推荐人
	 * @param customUuid 推荐人唯一标识
	 */
	@Async
	private void pushToSupCustomer(String customUuid, String phone){
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT CODE_DESC FROM ")
		.append(Table.T_APP_CODE_LIST)
		.append(" WHERE REC_ST = '").append(SystemConstant.REC_ST_1).append("'")
		.append(" AND CODE_TP = '").append(Code.PUSH_TEMPLET).append("'")
		.append(" AND CODE_VAL = 'CUSTOMER_REG'");
		List<Map<String, Object>> result = appCustomerInfoDao.queryForListMap(sql.toString(), new Object[]{});
		if(result == null || result.isEmpty()){
			return;
		}
		String content = String.valueOf(result.get(0).get("CODE_DESC")).replaceAll("X", phone);
		messageInfService.pushMessage(customUuid, null, "推荐佣金到账通知", content);
	}
}